package com.nave.view;

import nave.control.Options;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.nave.R;
import com.nave.utils.Database;
import com.nave.utils.SoundController;

public class HighScoresActivity extends ListActivity
{
	private Database db;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO is that it?
		super.onCreate(savedInstanceState);

		String cursorNames[] = { Database.KEY_NAME, Database.KEY_POINTS };
		int fields[] = { R.id.highscores_name, R.id.highscores_score };

		db = new Database(this);

        db.open();
		setListAdapter(new SimpleCursorAdapter(this, R.layout.scores,
				db.getAllTitles(), cursorNames, fields ));
        db.close();

        setContentView(R.layout.highscores);

		setupButtons();
		
		if ( Options.sound() && !MainMenu.mediaPlayer.isPlaying() ) MainMenu.mediaPlayer.start();
	}

	private void playClickSound()
    {
    	SoundController.getReference().
			playSound(SoundController.CLICK, getApplicationContext());
    }
	
	private void setupButtons()
	{
		Button back = (Button) findViewById(R.id.highscores_back);
		Button erase = (Button) findViewById(R.id.erase);

		back.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				playClickSound();
				HighScoresActivity.this.finish();
			}
		});
		erase.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				playClickSound();
				
				// TODO restyle the alert box
				AlertDialog.Builder prompt = new AlertDialog.Builder(HighScoresActivity.this);
				prompt.setTitle(R.string.confirm);
				prompt.setPositiveButton(R.string.ok, new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						playClickSound();

						// TODO use the bundle to fix it
						db.open();
						db.clear();
						db.close();
						// TODO prompt
						finish();
						Toast.makeText(HighScoresActivity.this,
								R.string.scoresErased, Toast.LENGTH_LONG).show();
					}
				});
				prompt.setNegativeButton(R.string.no, new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						playClickSound();
						dialog.cancel();
					}
				});
				prompt.show();
			}
		});
	}
}